import time
import cv2

start_time = time.time()
x = 1  # displays the frame rate every 1 second
counter = 0
window_name = "mark"
camera_idx = 1

# 读取视频，可以来自一段已存好的视频，也可以直接来自摄像头，通过0,1参数配置本机或usb摄像头
cap = cv2.VideoCapture(camera_idx)
while cap.isOpened():
    # while cap.isOpened():  # 循环检测每一帧
    ok, frame = cap.read()  # 读取一帧数据
    if not ok:
        break
    cv2.namedWindow(window_name)  # 参数window_name给创建的窗口命名

    # 告诉OpenCV使用人脸识别分类器,还是那个opencv自带的分类器，目录结构和《haar的简单应用》一样
    classfier = cv2.CascadeClassifier("../cascades/haarcascade_frontalface_default.xml")

    # 绿色勾边，RGB格式
    color = (0, 255, 0)



        # 将当前帧转换成灰度图像
    grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 人脸检测，1.2和2分别为图片缩放比例和需要检测的有效点数
    faceRects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))

    if len(faceRects) > 0:  # 大于0则检测到人脸
        for faceRect in faceRects:  # 单独框出每一张人脸
            x, y, w, h = faceRect
            cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 3)  # 5控制绿色框(勾边)的粗细

        # 显示图像
    cv2.imshow(window_name, frame)
    c = cv2.waitKey(10)
    if c & 0xFF == ord('q'):
        break

    counter += 1
    #if (time.time() - start_time) > x:
    print("FPS: ", counter / (time.time() - start_time))
    counter = 0
    start_time = time.time()
cap.release()
cv2.destroyAllWindows()

